package com.cfpamf.ms.insur.pay.integration.alipay;

import com.alipay.api.AlipayClient;
import com.alipay.api.DefaultAlipayClient;
import com.cfpamf.common.ms.exception.MSException;
import com.cfpamf.ms.insur.pay.config.AliPayConfig;
import com.cfpamf.ms.insur.pay.config.AliPayProperties;
import com.cfpamf.ms.insur.pay.constant.BizExceptEnum;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.stereotype.Component;

import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;

/**
 * 支付宝client工厂
 *
 * @author zhangnayi
 */
@Component
@EnableConfigurationProperties(AliPayConfig.class)
public class AliPayClientFactory {

    /**
     * client缓存
     */
    private static ConcurrentMap<String, AlipayClient> clientCache = new ConcurrentHashMap<>();

    /**
     * 支付宝多账户配置
     */
    @Autowired
    public AliPayConfig aliPayConfig;

    /**
     * 获取支付宝AlipayClient
     *
     * @param sourceSys
     * @return
     */
    public AlipayClient getAlipayClient(String sourceSys) {
        return clientCache.computeIfAbsent(sourceSys, k -> {
            AliPayProperties payProperty = getSystemAliPayProperty(sourceSys);
            return new DefaultAlipayClient(payProperty.getGatewayUrl(), payProperty.getAppId(),
                    payProperty.getMerchantPrivateKey(), AliPayConstants.ALIPAY_REQUEST_FORMAT_JSON,
                    AliPayConstants.CHARSET_UTF8, payProperty.getAlipayPublicKey(), payProperty.getSignType());
        });
    }

    /**
     * 获取业务系统支付宝配置参数
     *
     * @param sourceSys
     * @return
     */
    public AliPayProperties getSystemAliPayProperty(String sourceSys) {
        AliPayProperties properties = aliPayConfig.getBizSystemProperties().get(sourceSys);
        if (properties == null) {
            throw new MSException(BizExceptEnum.SYSTEM_CONFIG_ERROR);
        }
        return properties;
    }
}
